<?php

namespace app\admin\controller\vppz;

use app\common\controller\Backend;

use think\Session;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class VipCode extends Base
{

    /**
     * Order模型对象
     * @var \app\admin\model\vppz\Order
     */
    protected $model = null;

	protected $searchFields = ['id'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\VipCardPackage();
        $this->vipmodel = new \app\admin\model\vppz\VipPackage();
        $this->cardmodel = new \app\admin\model\vppz\VipCard();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
				$row->getRelation('admin')->visible(['username']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
     public function __get($name)
    {
        return Session::get('admin.' . $name);
    }
    //制作会员码
    public function add(){
        set_time_limit(0);
        $num = input('num',0);
        $is_hyaline = input('is_hyaline','0');

        $res = $this->vipmodel->whereNull('deletetime')->order('price','asc')->select();
        if(empty($res) === FALSE){
            foreach ($res as &$v){
                $v['duration'] = $v['duration'].'个月';
            }
        }
        if($this->request->isPost()){
            $package_id = input('package_id');
            $image = input('image','https://banyetang.oss-cn-beijing.aliyuncs.com/xiaochengxu/vipcard.png');
            if(empty($package_id)){
                $this->error('套餐选择有误');
            }
            if($num <= 0){
                $this->error('制作数量有误');
            }
            $package = $this->vipmodel->where('id',$package_id)->find();
            if(empty($package)){
                $this->error('套餐选择有误');
            }
            $opera = [];
            $this->cardmodel->startTrans();
             $admin = Session::get("admin");
            $this->model->save(array(
                'card_num'=>$num,
                'admin_id'=>$admin['id'],
                'image'=>$image,
                'vip_package_id' => $package_id,
                'vip_package_title'=>$package['title']
            ));
            $note_id =$this->model->id;
            $opera[] = $package_id;
            for ($i =0;$i < $num;$i++) {
                $code = uniqid();
                $accessToken = \Tools::getaccessToken();
                $scene = "vipcode=".$code;
                $page = 'vp_pz/pages/index/index';
                $resdata = \Wxchat::createqrcodeb($accessToken,$scene,$page,430,false,false,$is_hyaline);
                if($resdata['code'] == 1){
                    $file_path = 'uploads/vipcard/' . $code . '.png';
                    $pat = 'uploads/vipcard';
                    if (!is_dir($pat)) {
                        mkdir($pat, 0755, true);
                    }
                    file_put_contents($file_path, $resdata['data']);
                }else{
                    $opera[] = false;
                    break;
                }
                $cardData = array(
                    'code' => $code,
                    'package_id' => $note_id,
                    'vip_package_id' => $package_id,
                    'createtime'=>time(),
                    'updatetime'=>time(),
                    'status'=>0,
                    'duration'=>$package['duration'],
                    'vip_package_title'=>$package['title'],
                    'qrcode'=>'/'.$file_path
                );
                $opera[] = $this->cardmodel->insert($cardData);
            }
            if(\Tools::checkArrayResult($opera)){
                $this->cardmodel->commit();
                $this->success();
            }else{
                $this->cardmodel->rollback();
                $this->error('操作失败，请重试');
            }
        }
        $this->assign('packages',$res);
        return $this->view->fetch();
    }

    /**
     * 从下载队列下载
     */
    public function download()
    {
        $id = input('ids', '');
        error_reporting(E_ERROR);
        $cardPackage = $this->model->where(['id'=>$id])->find();
        if (empty($cardPackage) === FALSE) {
            $image = $cardPackage['image_url'];
            $cardLists = $this->cardmodel->where(['package_id'=>$id])->select();
            $filelist = [];
            $oldfile = [];

            if (!is_dir('uploads/cardsuccess')) {
                mkdir('uploads/cardsuccess', 0755, true);
            }
            foreach ($cardLists as $i => $v) {
                $qrcode = \addons\vppz\library\Vpower::dourl($v['qrcode']);
                $config = array(
                    'text' => array(),
                    'image' => array(
                        array(
                            'url' => $qrcode,       //图片资源路径
                            'left' => 1102,
                            'top' => 402,
                            'stream' => 0,             //图片资源是否是字符串图像流
                            'right' => 0,
                            'bottom' => 0,
                            'width' => 252,
                            'height' => 252,
                            'opacity' => 100
                        )
                    ),
                    'background' => $image,
                );
                $filename = 'uploads/cardsuccess/' . $v['code']. '.jpg';//本地图片 需要上传oss
                $respath = \Tools::createPoster($config, $filename);
                array_push($filelist, $filename);
                array_push($oldfile, $v);
            }
            $zip = new \ZipArchive;
            $zip_time = time() . ".zip"; // 压缩的目录名
            $zip_filename = "uploads/vipcardzip/" . $zip_time; // 指定一个压缩包地址
            if (!is_dir('uploads/vipcardzip')) {
                mkdir('uploads/vipcardzip', 0755, true);
            }
            $zip->open($zip_filename, \ZIPARCHIVE::CREATE); // 打开压缩包,没有则创建
//        // 参数1是要压缩的文件,参数2为压缩后,在压缩包中的文件名「这里我们把 demo1.php 文件压缩,压缩后的文件为 dd.php」,如果需要的压缩后的文件跟原文件名一样 addFile() 的第二个参数可以改为 basename("../alg/demo1.php"),也就是原文件所在的路径
            foreach ($filelist as $f) {
                $zip->addFile($f, basename($f));
            }
            $rs = $zip->close();
            header('Content-Type: application/download');
            header('Content-Disposition: attachment; filename=file.zip');
            readfile($zip_filename);
            if (file_exists($zip_filename)) {
                unlink($zip_filename);
            }
//            foreach ($filelist as $f) {
//                if (file_exists($f)) {
//                    unlink($f);
//                }
//            }
            exit;
        } else {
            $this->error('下载失败');
        }
    }
    public function downloadqrcode()
    {
        $id = input('ids', '');
        error_reporting(E_ERROR);
        $cardPackage = $this->model->where(['id'=>$id])->find();
        if (empty($cardPackage) === FALSE) {
            $image = $cardPackage['image_url'];
            $cardLists = $this->cardmodel->where(['package_id'=>$id])->select();
            $filelist = [];

            if (!is_dir('uploads/cardsuccess')) {
                mkdir('uploads/cardsuccess', 0755, true);
            }
            foreach ($cardLists as $i => $v) {
                array_push($filelist,ltrim($v['qrcode'],'/'));
            }
            $zip = new \ZipArchive;
            $zip_time = time() . ".zip"; // 压缩的目录名
            $zip_filename = "uploads/vipcardzip/" . $zip_time; // 指定一个压缩包地址
            if (!is_dir('uploads/vipcardzip')) {
                mkdir('uploads/vipcardzip', 0755, true);
            }
            $zip->open($zip_filename, \ZIPARCHIVE::CREATE); // 打开压缩包,没有则创建
//        // 参数1是要压缩的文件,参数2为压缩后,在压缩包中的文件名「这里我们把 demo1.php 文件压缩,压缩后的文件为 dd.php」,如果需要的压缩后的文件跟原文件名一样 addFile() 的第二个参数可以改为 basename("../alg/demo1.php"),也就是原文件所在的路径
            foreach ($filelist as $f) {
                $zip->addFile($f, basename($f));
            }
            $rs = $zip->close();
            header('Content-Type: application/download');
            header('Content-Disposition: attachment; filename=file.zip');
            readfile($zip_filename);
            if (file_exists($zip_filename)) {
                unlink($zip_filename);
            }
//            foreach ($filelist as $f) {
//                if (file_exists($f)) {
//                    unlink($f);
//                }
//            }
            exit;
        } else {
            $this->error('下载失败');
        }
    }
   /**
     * 服务设置
     */
    public function detail()
    {
		$ids = input('ids');
        $card = $this->cardmodel->get(['id' => $ids]);
        if (!$card) {
            $this->error(__('No Results were found'));
        }
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->cardmodel->whereIn('package_id',$ids)->delete();
        $this->model->whereIn('id',$ids)->delete();
        $this->success();
    }
}
